package com.share.config.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis 客户端
 * <p>
 * 坑:redis如果设置了过期时间---则需要设置时间单位否则会报错
 */
@Component
public class RedisClient {

    @Autowired
    private StringRedisTemplate template;

    public void set(String key, String value, long expire_seconds) {
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key, value, expire_seconds, TimeUnit.SECONDS);
    }

    public void set(String key, String value) {
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key, value);
    }

    public String get(String key) {
        ValueOperations<String, String> ops = this.template.opsForValue();
        return ops.get(key);
    }

    public Long increment(String key) {
        ValueOperations<String, String> ops = template.opsForValue();
        return ops.increment(key);
    }

    public Set<String> keys(String key) {
        return this.template.keys(key);
    }

    public void setex(String key, String value, int expire) {
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key, value, expire, TimeUnit.SECONDS);
    }

    public boolean del(String key) {
        return template.delete(key);
    }

    //h集合的操作
    public void hSet(String key, String hkey, String value) {
        template.opsForHash().put(key, hkey, value);
    }

    public String hGet(String key, String hkey) {
        return (String) template.opsForHash().get(key, hkey);
    }

    public List<Object> hmGet(String key, List<Object> hkeys) {
        return template.opsForHash().multiGet(key, hkeys);
    }

    public Map<String, String> hGetAll(String key) {
        HashOperations<String, String, String> ops = template.opsForHash();
        Map<String, String> entries = ops.entries(key);
        return entries;
    }

    public void hDel(String key, String hkey) {
        if (StringUtils.isBlank(hkey)) {
            template.opsForHash().delete(key);
        } else {
            template.opsForHash().delete(key, hkey);
        }
    }

    public void hDelAll(String key) {
        template.opsForHash().delete(key);
    }

    /**
     * 发布与订阅
     *
     * @param channel
     * @param message
     */
    public void convertAndSend(String channel, String message) {
        template.convertAndSend(channel, message);
    }
}
